package cn.momoshenchi.controller;

import cn.momoshenchi.pojo.BookDetail;
import cn.momoshenchi.service.BookDetailService;
import cn.momoshenchi.service.UserBookService;
import cn.momoshenchi.util.AssertUtil;
import cn.momoshenchi.util.ResultInfo;
import cn.momoshenchi.pojo.Book;
import cn.momoshenchi.util.PageUtil;
import cn.momoshenchi.service.BookService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.IOException;
import java.util.List;

/**
 * @version : 1.0
 * @author: momoshenchi
 * @date: 2021/6/7 - 22:05
 */
@RestController
@RequestMapping("book")
public class BookController
{

    @Autowired
    private BookService bookService;

    @Autowired
    private BookDetailService bookDetailService;

    @Autowired
    private UserBookService userBookService;

    @GetMapping("list")
    @Operation(summary = "查询书籍信息")
    public ResultInfo list( PageUtil page)
    {
        IPage<Book> bookPage =new Page<>(page.getPage(), page.getSize());
        bookPage = bookService.page(bookPage);
        return  new ResultInfo(bookPage);
    }


    @GetMapping("{bookId}")
    @Operation(summary = "通过Id查询书籍")
    public ResultInfo list(@PathVariable Long bookId)
    {
        Book book = bookService.getById(bookId);
        return  new ResultInfo(book);
    }

    @PostMapping("insert")
    @Operation(summary = "添加书籍")
    public ResultInfo insert(@RequestBody Book book) throws IOException
    {
       bookService.insertWithEs(book);
        return  new ResultInfo();
    }

    @PostMapping("insertList")
    @Operation(summary = "批量添加书籍")
    public ResultInfo insertList(@RequestBody List<Book> book) throws IOException
    {
        bookService.insertListWithEs(book);
        return  new ResultInfo();
    }

    @PostMapping("update")
    @Operation(summary = "更新书籍")
    public ResultInfo update(@RequestBody Book book)
    {
        AssertUtil.isTrue(!bookService.updateById(book),"更新失败");
        return  new ResultInfo();
    }

    @GetMapping("detail/{bookId}")
    @Operation(summary = "通过Id查询书籍详情")
    public ResultInfo detail(@PathVariable Long bookId)
    {
        BookDetail book = bookDetailService.getById(bookId);
        return  new ResultInfo(book);
    }
}
